package com.zyc.studentstudy.utils

import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.util.Log
import java.lang.reflect.InvocationTargetException

object ContextHolder {
    private const val TAG = "ContextHolder"

    private var mApplication: Application? = null

    // 在自定义的Application中初始化.
    @JvmStatic
    fun init(application: Application) {
        mApplication = application
    }

    @JvmStatic
    fun getResources(): Resources {
        return getApplication().resources
    }

    // 发送普通的广播
    @JvmStatic
    fun sendBroadcast(intent: Intent) {
        getApplication().sendBroadcast(intent)
    }

    @JvmStatic
    fun getApplicationContext(): Context {
        return getApplication().applicationContext
    }

    @JvmStatic
    fun getApplication(): Application {
        if (mApplication != null) {
            return mApplication!!
        }
        var application: Application? = null
        try {
            val method = Class.forName("android.app.ActivityThread").getDeclaredMethod("currentApplication")
            application = method.invoke(null) as Application?

            if (application == null) {
                val method1 = Class.forName("android.app.AppGlobals").getMethod("getInitialApplication")
                application = method1.invoke(null) as Application?
            }
        } catch (e: NoSuchMethodException) {
            Log.e(TAG, e.toString())
        } catch (e: ClassNotFoundException) {
            Log.e(TAG, e.toString())
        } catch (e: IllegalAccessException) {
            Log.e(TAG, e.toString())
        } catch (e: InvocationTargetException) {
            Log.e(TAG, e.toString())
        } finally {
            mApplication = application
        }
        return application!!
    }
}